home *** CD-ROM | disk | FTP | other *** search
/ Apple Developer Connection Student Program / ADC Tools Sampler CD Disk 3 1999.iso / Documentation / Books / Learn Java on the Macintosh / Learn Java Projects / 08.04 - next prime / NextPrime.java < prev    next >
Text File  |  1996-04-22  |  2KB  |  47 lines

  1. /* -------------------------------------------------------------
  2. This applet finds the next prime number after a starting point.
  3.  
  4. Java's classes: Applet    (applet)
  5.                 System    (lang)
  6.                 Math      (lang)
  7.  
  8. Custom classes: NextPrime
  9.  
  10. ------------------------------------------------------------- */
  11.  
  12. public class NextPrime extends java.applet.Applet {
  13.     public void init() {
  14.    
  15.         int     startingPoint, candidate, last, i;
  16.         boolean isPrime;
  17.  
  18.         startingPoint = 19;
  19.  
  20.         if ( startingPoint < 2 ) {
  21.                candidate = 2;
  22.         } else if ( startingPoint == 2 ) {
  23.             candidate = 3;
  24.         } else {
  25.         
  26.                candidate = startingPoint;
  27.             if (candidate % 2 == 0)                  /* Test only odd numbers */
  28.                 candidate--;
  29.             do {
  30.             
  31.                 isPrime = true;                      /* Assume glorious success */
  32.                 candidate += 2;                      /* Bump to the next number to test */
  33.                 last = (int)Math.sqrt( candidate );  /* We'll check to see if candidate */
  34.                                                      /* has any factors, from 2 to last */
  35.                                                      
  36.                    /* Loop through odd numbers only */
  37.                 for ( i = 3; (i <= last) && isPrime; i += 2 ) {
  38.                        if ( (candidate % i) == 0 )
  39.                         isPrime = false;
  40.                    }
  41.             } while ( ! isPrime );
  42.            }
  43.  
  44.         System.out.println( "The next prime after " + startingPoint + " is " + candidate);
  45.         
  46.     }
  47. }